import React, {useEffect, useState} from 'react';
import {Building2, ChevronDown, ChevronRight, Edit2, Search, Trash2, UserPlus, Users} from 'lucide-react';
import DeleteConfirmModal from '../../components/modals/DeleteConfirmModal';
import UserFormModal from '../../components/modals/UserFormModal';
import {Req} from "../../util/fetch.ts";

interface User {
    id: number;
    name: string;
    realname: string;
    avatar: string;
    gender: '0' | '1';
    birthday: string;
    phone: string;
    region: string;
    team: string;
    department: string;
    position: string;
    role: 'user' | 'admin';
}

interface Department {
    id: number;
    name: string;
    users?: any[];
}

interface Team {
    id: number;
    name: string;
    departments: Department[];
}

interface Region {
    id: number;
    name: string;
    teams: Team[];
}

// 模拟数据
const mockRegions: Region[] = [];

export default function AdminUsers() {
    const [searchTerm, setSearchTerm] = useState('');
    // const [showFilters, setShowFilters] = useState(false);
    const [expandedRegions, setExpandedRegions] = useState<number[]>([]);
    const [expandedTeams, setExpandedTeams] = useState<number[]>([]);
    const [selectedDept, setSelectedDept] = useState<Department | null>(null);
    const [showUserModal, setShowUserModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [modalMode, setModalMode] = useState<'add' | 'edit'>('add');
    const [regions, setRegions] = useState<Region[]>(mockRegions);
    const [roles, setRoles] = useState<any>([]);

    const toggleRegion = (regionId: number) => {
        setExpandedRegions(prev =>
            prev.includes(regionId)
                ? prev.filter(id => id !== regionId)
                : [...prev, regionId]
        );
    };

    const toggleTeam = (teamId: number) => {
        setExpandedTeams(prev =>
            prev.includes(teamId)
                ? prev.filter(id => id !== teamId)
                : [...prev, teamId]
        );
    };

    const handleAddUser = () => {
        setModalMode('add');
        setSelectedUser(null);
        setShowUserModal(true);
    };

    const handleEditUser = (user: User) => {
        console.log('handleEditUser', user);
        setModalMode('edit');
        setSelectedUser(user);
        setShowUserModal(true);
    };

    const handleDeleteUser = (user: User) => {
        setSelectedUser(user);
        setShowDeleteModal(true);
    };

    const handleSaveUser = async (userData: any) => {
        console.log('handleSaveUser', userData)
        const user = {
            id: userData.id,
            birthday: userData.birthday?.substr(0, 10),
            position: userData.position,
            password: userData.password,
            sex: userData.gender,
            departId: userData.departId,
            phone: userData.phone,
            areaId: userData.areaId,
            teamId: userData.teamId,
            realname: userData.realname,
            type: userData.role === 'admin' ? 0 : 1,
            username: userData.phone,
            roleId: userData.roleId,
        }
        const method = modalMode === 'edit' ? 'PUT' : 'POST';
        const url = modalMode === 'edit' ? `/sysUser/edit` : '/sysUser/add';
        const res = await Req(url, {
            method,
            body: user,
            headers: {}
        })
        if (res.success) {
            queryAreaTree()
            setShowUserModal(false);
            setSelectedDept({
                ...selectedDept,
                users: [...selectedDept.users.filter(u => u.id !== selectedUser.id), user]
            })
            setSelectedUser(null);
        }
        alert(res.message)
    };

    const handleConfirmDelete = async () => {
        if (selectedUser) {
            await Req(`/sysUser/batch?ids=${selectedUser.id}`, {method: 'DELETE'});
            setSelectedDept({...selectedDept, users: selectedDept.users.filter(u => u.id !== selectedUser.id)});
            setShowDeleteModal(false);
            queryAreaTree()
            setSelectedUser(null);
            alert('删除成功');
        }
    };

    const queryAreaTree = async () => {
        const res = await Req('/bsArea/tree');
        setRegions(res.data);
    }

    const queryRoleList = async () => {
        const res = await Req(`/sysRole/list`)
        if (res.success) {
            setRoles(res.data)
        } else {
            alert(res.message)
        }
    };

    useEffect(() => {
        queryAreaTree()
        queryRoleList()
    }, []);

    return (
        <div>
            <div className="mb-8">
                <h1 className="text-2xl font-bold text-gray-900">用户管理</h1>
                <p className="text-gray-500">管理系统中的所有用户</p>
            </div>

            {/* 工具栏 */}
            <div className="flex justify-between items-center mb-6">
                <div className="flex items-center space-x-4">
                    <div className="relative w-64">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-5 h-5"/>
                        <input
                            type="text"
                            placeholder="搜索用户..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full pl-10 pr-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                    </div>
                    {/*<button*/}
                    {/*    onClick={() => setShowFilters(!showFilters)}*/}
                    {/*    className={`p-2 rounded-lg ${*/}
                    {/*        showFilters ? 'bg-blue-500 text-white' : 'bg-gray-100 text-gray-600'*/}
                    {/*    }`}*/}
                    {/*>*/}
                    {/*    <Filter className="w-5 h-5"/>*/}
                    {/*</button>*/}
                </div>
                <button
                    onClick={handleAddUser}
                    className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
                >
                    <UserPlus className="w-5 h-5 mr-2"/>
                    添加用户
                </button>
            </div>

            {/* 主内容区 - 两栏布局 */}
            <div className="flex gap-6">
                {/* 左侧组织结构树 */}
                <div className="w-1/3 bg-white rounded-xl shadow-sm p-4">
                    <h2 className="text-lg font-semibold mb-4">组织结构</h2>
                    <div className="space-y-2">
                        {regions.map(region => (
                            <div key={region.id} className="select-none">
                                {/* 地区 */}
                                <button
                                    onClick={() => toggleRegion(region.id)}
                                    className="flex items-center w-full text-left p-2 hover:bg-gray-50 rounded-lg"
                                >
                                    {expandedRegions.includes(region.id) ? (
                                        <ChevronDown className="w-5 h-5 text-gray-400 mr-2"/>
                                    ) : (
                                        <ChevronRight className="w-5 h-5 text-gray-400 mr-2"/>
                                    )}
                                    <Building2 className="w-5 h-5 text-blue-500 mr-2"/>
                                    <span className="font-medium">{region.name}</span>
                                </button>

                                {/* 团队 */}
                                {expandedRegions.includes(region.id) && (
                                    <div className="ml-6 space-y-2">
                                        {region.teams.map(team => (
                                            <div key={team.id}>
                                                <button
                                                    onClick={() => toggleTeam(team.id)}
                                                    className="flex items-center w-full text-left p-2 hover:bg-gray-50 rounded-lg"
                                                >
                                                    {expandedTeams.includes(team.id) ? (
                                                        <ChevronDown className="w-5 h-5 text-gray-400 mr-2"/>
                                                    ) : (
                                                        <ChevronRight className="w-5 h-5 text-gray-400 mr-2"/>
                                                    )}
                                                    <Users className="w-5 h-5 text-green-500 mr-2"/>
                                                    <span className="font-medium">{team.name}</span>
                                                </button>

                                                {/* 部门 */}
                                                {expandedTeams.includes(team.id) && (
                                                    <div className="ml-6 space-y-2">
                                                        {team.departments.map(dept => (
                                                            <button
                                                                key={dept.id}
                                                                onClick={() => setSelectedDept(dept)}
                                                                className={`flex items-center w-full text-left p-2 rounded-lg ${
                                                                    selectedDept?.id === dept.id
                                                                        ? 'bg-blue-50 text-blue-600'
                                                                        : 'hover:bg-gray-50'
                                                                }`}
                                                            >
                                                                <Building2 className="w-5 h-5 mr-2"/>
                                                                <span className="font-medium">{dept.name}</span>
                                                                <span className="ml-auto text-sm text-gray-500">
                                  {dept.users?.length || 0}人
                                </span>
                                                            </button>
                                                        ))}
                                                    </div>
                                                )}
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        ))}
                    </div>
                </div>

                {/* 右侧用户列表 */}
                <div className="flex-1 bg-white rounded-xl shadow-sm p-4">
                    <h2 className="text-lg font-semibold mb-4">
                        {selectedDept ? `${selectedDept.name} - 用户列表` : '所有用户'}
                    </h2>
                    <div className="space-y-4">
                        {selectedDept?.users?.filter(user => searchTerm == '' || user.realname.includes(searchTerm)).map(user => (
                            <div
                                key={user.id}
                                className="flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all"
                            >
                                <div className="flex items-center space-x-4">
                                    <img
                                        src={'https://img1.baidu.com/it/u=2318884743,3754999155&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'}
                                        alt={user.name}
                                        className="w-10 h-10 rounded-full"
                                    />
                                    <div>
                                        <div className="font-medium text-gray-900">{user.realname}</div>
                                        <div className="text-sm text-gray-500">{user.position}</div>
                                    </div>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <button
                                        onClick={() => handleEditUser(user)}
                                        className="p-2 text-gray-400 hover:text-blue-500 transition-colors"
                                    >
                                        <Edit2 className="w-5 h-5"/>
                                    </button>
                                    <button
                                        onClick={() => handleDeleteUser(user)}
                                        className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                                    >
                                        <Trash2 className="w-5 h-5"/>
                                    </button>
                                </div>
                            </div>
                        ))}
                        {(!selectedDept || !selectedDept.users?.length) && (
                            <div className="text-center py-8 text-gray-500">
                                {selectedDept ? '该部门暂无用户' : '请选择部门查看用户'}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* 用户表单模态框 */}
            {showUserModal && (
                <UserFormModal
                    mode={modalMode}
                    userData={selectedUser || undefined}
                    regions={regions}
                    roles={roles}
                    onClose={() => {
                        setShowUserModal(false);
                        setSelectedUser(null);
                    }}
                    onSave={handleSaveUser}
                />
            )}

            {/* 删除确认模态框 */}
            {showDeleteModal && selectedUser && (
                <DeleteConfirmModal
                    title="删除用户"
                    message={`确定要删除用户"${selectedUser.realname}"吗？此操作不可恢复。`}
                    onConfirm={handleConfirmDelete}
                    onCancel={() => {
                        setShowDeleteModal(false);
                        setSelectedUser(null);
                    }}
                />
            )}
        </div>
    );
}